//
//  MNDFingerLockViewController.m
//  minidai
//
//  Created by 谭谭伟 on 2017/6/6.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDFingerLockViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "MNDGestureViewController.h"

@interface MNDFingerLockViewController ()

@end

@implementation MNDFingerLockViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissAction:) name:@"dismissFingerVC" object:nil];
    [self evaluateAuthenticate];
    [self setupUI];
    // Do any additional setup after loading the view.
}

- (UILabel *)tipLabel {
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc]init];
    }
    return _tipLabel;
}

- (void)setupUI {
    [self.view addSubview:self.tipLabel];
//    self.tipLabel.text = @"hahahhahahahah";
    self.tipLabel.textColor = kColorBlack;
    self.tipLabel.font = [UIFont systemFontOfSize:13];
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.fingerTipLabel);
    }];
}

#pragma mark - Action
- (void)dismissAction:(NSNotification *)notification {
    [self dismissViewControllerAnimated:NO completion:nil];
}
//指纹验证
- (IBAction)fingerUnlockAction:(UIButton *)sender {
    [self evaluateAuthenticate];
}

- (IBAction)clickButtonFinger:(UIButton *)sender {
    [self evaluateAuthenticate];
}


//手势验证
- (IBAction)showGestureAction:(UIButton *)sender {
   
    //取到保存的密码
    NSString *password= [UserDefaultsTool objectForKey:kGesturePassword];
    if (password && password.length > 0) {
        if (self.dismissGestureVC == YES) {
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Gesture" bundle:nil];
            MNDGestureViewController *gestureViewcontroller = [storyBoard instantiateViewControllerWithIdentifier:@"MNDGestureViewController"];
            gestureViewcontroller.view.backgroundColor = [UIColor whiteColor];
            MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
            gestureViewcontroller.tipLabel.text = [NSString stringWithFormat:@"欢迎，%@", user.user_name];
            gestureViewcontroller.isCloseGesture = NO;
            gestureViewcontroller.topGestureView.hidden = YES;
            gestureViewcontroller.topLogImgV.hidden = NO;
            gestureViewcontroller.dismissFingerVC = YES;
            //        gestureViewcontroller.isHiddenTopView = YES;
            gestureViewcontroller.navigationController.navigationBarHidden = NO;
            gestureViewcontroller.forgetGestureButton.hidden = NO;
            gestureViewcontroller.fingerBtn.hidden = NO;
            [self presentViewController:gestureViewcontroller animated:YES completion:nil];
            void(^dismissVCBlock)(void) = ^(){
                [self dismissViewControllerAnimated:YES completion:^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"dismissFingerVC" object:nil];
                }];
            };
            gestureViewcontroller.dismissVCBlock = dismissVCBlock;
                }
    } else {
        [NetworkProgressHUD showHudMsg:@"您还没有开启手势密码"];
    }
    
    
}

//指纹解锁验证
- (void)evaluateAuthenticate
{
    //iOS8.0后才支持指纹识别接口
    if ([UIDevice currentDevice].systemVersion.floatValue < 8.0) {
        //弹出，该设备不支持指纹解锁
        [NetworkProgressHUD showHudMsg:@"该设备不支持指纹解锁"];
        return;
    }
    //创建LAContext
    LAContext* context = [[LAContext alloc] init];
    NSError* error = nil;
    NSString* result = @"通过Home键验证已有手机指纹";
    
    //首先使用canEvaluatePolicy 判断设备支持状态
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error]) {
        //支持指纹验证
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:result reply:^(BOOL success, NSError *error) {
            if (success) {
                NSLog(@"=======%@======",context);
                //验证成功，dismiss密码验证 ，弹出指纹开启成功
//                [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissGestureVC" object:nil];
                [NetworkProgressHUD showHudMsg:@"验证成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self dismissViewControllerAnimated:YES completion:^{
                        
                    }];
                });
//                if (self.fingerDismissVCBlock != nil) {
                
//                    self.fingerDismissVCBlock();
//                    return;
//                }
            }
            else
            {

                NSLog(@"%@",error.localizedDescription);
                switch (error.code) {
                    case LAErrorSystemCancel:
                    {
                        //系统取消授权，如其他APP切入
                        break;
                    }
                    case LAErrorUserCancel:
                    {
                        //用户取消验证Touch ID
                        break;
                    }
                    case LAErrorAuthenticationFailed:
                    {
                        //授权失败 ，弹出验证失败
                        [NetworkProgressHUD showHudMsg:@"验证失败"];
                        break;
                    }
                    case LAErrorPasscodeNotSet:
                    {
                        //系统未设置密码
                        break;
                    }
                    case LAErrorTouchIDNotAvailable:
                    {
                        //设备Touch ID不可用，例如未打开
                        [NetworkProgressHUD showHudMsg:@"设备未开启指纹功能"];
                        break;
                    }
                    case LAErrorTouchIDNotEnrolled:
                    {
                        //设备Touch ID不可用，用户未录入
                        [NetworkProgressHUD showHudMsg:@"Touch ID不可用"];
                        break;
                    }
                    case LAErrorUserFallback:
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //用户选择输入密码，切换主线程处理
                            
                        }];
                        break;
                    }
                    default:
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //其他情况，切换主线程处理
                        }];
                        break;
                    }
                }
            }
        }];
    }
    else
    {
        //不支持指纹识别，LOG出错误详情
        NSLog(@"不支持指纹识别");
//        [NetworkProgressHUD showHudMsg:@"设备不支持指纹识别"];
        
        switch (error.code) {
            case LAErrorTouchIDNotEnrolled:
            {
                NSLog(@"TouchID is not enrolled");
                break;
            }
            case LAErrorPasscodeNotSet:
            {
                NSLog(@"A passcode has not been set");
                break;
            }
            default:
            {
                NSLog(@"TouchID not available");
                break;
            }
        }
        
        NSLog(@"%@",error.localizedDescription);
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
